/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.gzchengguo.cn
* 注意：
* 本软件为www.gzchengguo.cn开发研制，未经购买不得商用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package link.chengguo.orangemall.modules.activity.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import link.chengguo.orangemall.api.OrangeException;
import link.chengguo.orangemall.common.service.impl.BaseServiceImpl;
import link.chengguo.orangemall.common.utils.QueryHelpPlus;
import link.chengguo.orangemall.dozer.service.IGenerator;
import link.chengguo.orangemall.enums.BillDetailEnum;
import link.chengguo.orangemall.enums.PayTypeEnum;
import link.chengguo.orangemall.enums.ShopCommonEnum;
import link.chengguo.orangemall.exception.BadRequestException;
import link.chengguo.orangemall.modules.activity.domain.OrangeUserExtract;
import link.chengguo.orangemall.modules.activity.param.UserExtParam;
import link.chengguo.orangemall.modules.activity.service.OrangeUserExtractService;
import link.chengguo.orangemall.modules.activity.service.dto.OrangeUserExtractDto;
import link.chengguo.orangemall.modules.activity.service.dto.OrangeUserExtractQueryCriteria;
import link.chengguo.orangemall.modules.activity.service.mapper.OrangeUserExtractMapper;
import link.chengguo.orangemall.modules.user.domain.OrangeUser;
import link.chengguo.orangemall.modules.user.service.OrangeUserBillService;
import link.chengguo.orangemall.modules.user.service.OrangeUserService;
import link.chengguo.orangemall.utils.FileUtil;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;


/**
* @author chengguo
* @date 2020-05-13
*/
@Service
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class OrangeUserExtractServiceImpl extends BaseServiceImpl<OrangeUserExtractMapper, OrangeUserExtract> implements OrangeUserExtractService {

    private final IGenerator generator;
    private final OrangeUserExtractMapper orangeUserExtractMapper;
    private final OrangeUserService userService;
    private final OrangeUserBillService billService;


    /**
     * 开始提现
     * @param userInfo 用户
     * @param param UserExtParam
     */
    @Override
    public void userExtract(OrangeUser userInfo, UserExtParam param) {
        BigDecimal extractPrice = userInfo.getBrokeragePrice();
        if(extractPrice.compareTo(BigDecimal.ZERO) <= 0) {
            throw new OrangeException("提现佣金不足");
        }

        double money = Double.valueOf(param.getMoney());
        if( extractPrice.compareTo(BigDecimal.valueOf(money)) < 0) {
            throw new OrangeException("提现佣金不足");
        }

        if(money <= 0) {
            throw new OrangeException("提现佣金大于0");
        }

        double balance = NumberUtil.sub(extractPrice.doubleValue(),money);
        if(balance < 0) {
            balance = 0;
        }

        OrangeUserExtract userExtract = new OrangeUserExtract();
        userExtract.setUid(userInfo.getUid());
        userExtract.setExtractType(param.getExtractType());
        userExtract.setExtractPrice(new BigDecimal(param.getMoney()));
        userExtract.setBalance(BigDecimal.valueOf(balance));

        if(StrUtil.isNotEmpty(param.getName())){
            userExtract.setRealName(param.getName());
        }else {
            userExtract.setRealName(userInfo.getNickname());
        }

        if(StrUtil.isNotEmpty(param.getWeixin())){
            userExtract.setWechat(param.getWeixin());
        }else {
            userExtract.setWechat(userInfo.getNickname());
        }

        String mark = "";

        if(PayTypeEnum.ALI.getValue().equals(param.getExtractType())){
            if(StrUtil.isEmpty(param.getAlipayCode())){
                throw new OrangeException("请输入支付宝账号");
            }
            userExtract.setAlipayCode(param.getAlipayCode());
            mark = "使用支付宝提现"+param.getMoney()+"元";
        }else if(PayTypeEnum.WEIXIN.getValue().equals(param.getExtractType())){
            if(StrUtil.isEmpty(param.getWeixin())){
                throw new OrangeException("请输入微信账号");
            }
            mark = "使用微信提现"+param.getMoney()+"元";
        }

        orangeUserExtractMapper.insert(userExtract);

        //更新佣金
        OrangeUser orangeUser = new OrangeUser();
        orangeUser.setBrokeragePrice(BigDecimal.valueOf(balance));
        orangeUser.setUid(userInfo.getUid());
        userService.updateById(orangeUser);

        //插入流水
        billService.expend(userInfo.getUid(),"佣金提现", BillDetailEnum.CATEGORY_1.getValue(),
                BillDetailEnum.TYPE_4.getValue(),money,balance, mark);

    }

    /**
     * 累计提现金额
     * @param uid uid
     * @return double
     */
    @Override
    public double extractSum(Long uid) {
        return orangeUserExtractMapper.sumPrice(uid);
    }


    //==============================================================//

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(OrangeUserExtractQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<OrangeUserExtract> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), OrangeUserExtractDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<OrangeUserExtract> queryAll(OrangeUserExtractQueryCriteria criteria){
        return baseMapper.selectList(QueryHelpPlus.getPredicate(OrangeUserExtract.class, criteria));
    }


    @Override
    public void download(List<OrangeUserExtractDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (OrangeUserExtractDto orangeUserExtract : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" uid",  orangeUserExtract.getUid());
            map.put("名称", orangeUserExtract.getRealName());
            map.put("bank = 银行卡 alipay = 支付宝wx=微信", orangeUserExtract.getExtractType());
            map.put("银行卡", orangeUserExtract.getBankCode());
            map.put("开户地址", orangeUserExtract.getBankAddress());
            map.put("支付宝账号", orangeUserExtract.getAlipayCode());
            map.put("提现金额", orangeUserExtract.getExtractPrice());
            map.put(" mark",  orangeUserExtract.getMark());
            map.put(" balance",  orangeUserExtract.getBalance());
            map.put("无效原因", orangeUserExtract.getFailMsg());
            map.put(" failTime",  orangeUserExtract.getFailTime());
            map.put("-1 未通过 0 审核中 1 已提现", orangeUserExtract.getStatus());
            map.put("微信号", orangeUserExtract.getWechat());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 操作提现
     * @param resources OrangeUserExtract
     */
    @Override
    public void doExtract(OrangeUserExtract resources){
        if(resources.getStatus() == null){
            throw new BadRequestException("请选择审核状态");
        }

        if(ShopCommonEnum.EXTRACT_0.getValue().equals(resources.getStatus())){
            throw new BadRequestException("请选择审核状态");
        }
        if(ShopCommonEnum.EXTRACT_MINUS_1.getValue().equals(resources.getStatus())){
            if(StrUtil.isEmpty(resources.getFailMsg())){
                throw new BadRequestException("请填写失败原因");
            }
            String mark = "提现失败,退回佣金"+resources.getExtractPrice()+"元";
            OrangeUser orangeUser = userService.getById(resources.getUid());

            double balance = NumberUtil.add(orangeUser.getBrokeragePrice(),resources.getExtractPrice()).doubleValue();
            //插入流水
            billService.income(resources.getUid(),"提现失败", BillDetailEnum.CATEGORY_1.getValue(),
                    BillDetailEnum.TYPE_4.getValue(),resources.getExtractPrice().doubleValue(),balance,
                    mark,resources.getId().toString());

            //返回提现金额
            userService.incBrokeragePrice(resources.getExtractPrice(),resources.getUid());

            resources.setFailTime(new Date());

        }

        //todo 此处为企业付款，没经过测试
        /**
         boolean isTest = true;
         if(!isTest){
         OrangeWechatUserDto wechatUser =  generator.convert(wechatUserService.getOne(new QueryWrapper<OrangeWechatUser>().eq("uid",resources.getUid())),OrangeWechatUserDto.class);
         if(ObjectUtil.isNotNull(wechatUser)){
         try {
         payService.entPay(wechatUser.getOpenid(),resources.getId().toString(),
         resources.getRealName(),
         resources.getExtractPrice().multiply(new BigDecimal(100)).intValue());
         } catch (WxPayException e) {
         throw new BadRequestException(e.getMessage());
         }
         }else{
         throw new BadRequestException("不是微信用户无法退款");
         }

         }
         **/

        this.saveOrUpdate(resources);
    }
}
